{ config, lib, pkgs, ... }:

{
  config = {
    nixpkgs.hostPlatform = "x86_64-linux";

    system-manager.allowAnyDistro = true;

    environment = {
      etc = {
        "wsl.conf".text = ''
          [boot]
          systemd=true
        '';

        "nix/nix.conf".text = ''
          substituters = https://mirrors.ustc.edu.cn/nix-channels/store https://cache.nixos.org/
          extra-experimental-features = nix-command flakes
          build-users-group = nixbld
        '';

        "apt/sources.list".text = ''
          # 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
          deb https://mirrors.tuna.tsinghua.edu.cn/debian/ testing main contrib non-free non-free-firmware
          # deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ testing main contrib non-free non-free-firmware

          deb https://mirrors.tuna.tsinghua.edu.cn/debian/ testing-updates main contrib non-free non-free-firmware
          # deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ testing-updates main contrib non-free non-free-firmware

          deb https://mirrors.tuna.tsinghua.edu.cn/debian/ testing-backports main contrib non-free non-free-firmware
          # deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ testing-backports main contrib non-free non-free-firmware

          # 以下安全更新软件源包含了官方源与镜像站配置，如有需要可自行修改注释切换
          deb https://mirrors.tuna.tsinghua.edu.cn/debian-security testing-security main contrib non-free non-free-firmware
          # deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security testing-security main contrib non-free non-free-firmware
        '';
      };

      systemPackages = with pkgs; [
        postgresql
      ];
    };

    systemd.services = {
      postgresql = {
        enable = true;

        # Unit
        description = "PostgreSQL database server";
        after = [ "network-online.target" ];

        # Service
        serviceConfig = {
          ExecStart = "${pkgs.postgresql}/bin/pg_ctl start -D /data/postgresql";
          ExecStop = "${pkgs.postgresql}/bin/pg_ctl stop -D /data/postgresql";
          ExecReload = "${pkgs.postgresql}/bin/pg_ctl restart -D /data/postgresql";
          User = "postgres";
          Group = "postgres";
          Restart = "on-failure";

          Type = "forking";
        };

        wantedBy = [ "default.target" ];
      };
      ollama = {
        enable = true;

        # Unit
        description = "Ollama Service";
        after = [ "network-online.target" ];

        # Service
        serviceConfig = {
          ExecStart = "/usr/local/bin/ollama serve";
          User = "ollama";
          Group = "ollama";
          Restart = "always";
          RestartSec = 3;
          Environment = "OLLAMA_NUM_PARALLEL=1;OLLAMA_MAX_LOADED_MODELS=1";
        };

        # Install
        wantedBy = [ "default.target" ];
      };
    };
  };
}
